package com.swift.maintenance.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.common.JsonInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.dao.UserDao;
import com.jiyi.easemob.util.EaseMobHelp;
import com.swift.base.ActivityBase;
import com.swift.base.ApplicationBase;
import com.swift.bean.EntityBase;
import com.swift.bean.LoginUser;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.bean.Company;
import com.swift.maintenance.bean.User;
import com.swift.maintenance.utils.JPushUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.EncryptUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.DbException;

import java.lang.reflect.Type;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//import com.jiyi.activity.ProprietorActivity;
//import com.jiyi.activity.SuperviseActivity;

public class LoginActivity extends ActivityBase {

    public static final int SUCCESS_CODE = 0;

    // 监管
    public static final int SUPERVISE_TYPE = 0;
    // 业主
    public static final int PROPRIETOR_TYPE = 1;
    // 维保
    public static final int MAINTENANCE_TYPE = 6;

    private UserDao userDao = new UserDao(this);

    @BindView(R.id.btn_login_login)
    Button btnLogin;

    @BindView(R.id.edt_login_user)
    EditText edtUser;

    @BindView(R.id.edt_lgoin_password)
    EditText edtPassword;

    @BindView(R.id.cb_login_remember)
    CheckBox cbRemember;

//    @BindView(R.id.cb_resetdb)
//    CheckBox cbResetdb;

    @BindView(R.id.tvRegist)
    TextView tvRegist;

    private ProgressDialog dialog;

    private String user;

    private String pwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        if (UserInfoUtil.isLogin()) {
            //设置免打扰圈
            EaseMobHelp.getInstance().initUnBlockGroupId();
            gotoByRole(UserInfoUtil.getCurrentUserRole());
            finish();
        } else {
            //环信用户先注销 环信机制问题 先注销再登陆 不然发送消息会失败
            EaseMobHelp.getInstance().logout();
            restoreInputValue();
        }

    }

    @OnClick({R.id.btn_login_login,R.id.tvRegist})
    public void onLoginClick(View v) {
        switch (v.getId())
        {
            case R.id.btn_login_login:
                login();
                break;
            case R.id.tvRegist:
                regist();
                break;
        }


    }

    private void parseJSON(String jsonString) {

        try {
            JSONObject jnbString = new JSONObject(jsonString);
            JSONObject jnb = jnbString.getJSONObject("message");

            String userInfo = jnb.getString("user");
            LoginUser users = new Gson().fromJson(userInfo, LoginUser.class);
            LoginUser.setInstance(users);

            ApplicationBase.LocalData
                    .edit()
                    .putString(AppConfig.ACCESS_TOKEN,
                            (String) jnb.get("access-token")).commit();
            ApplicationBase.LocalData.edit()
                    .putString("account", LoginUser.getInstance().getAccount())
                    .commit();
            ApplicationBase.LocalData
                    .edit()
                    .putString("depart_code",
                            LoginUser.getInstance().getDepart_code()).commit();
            ApplicationBase.LocalData
                    .edit()
                    .putInt(AppConfig.DEPART_ID,
                            LoginUser.getInstance().getDepart_id()).commit();
            ApplicationBase.LocalData
                    .edit()
                    .putString("depart_name",
                            LoginUser.getInstance().getDepart_name()).commit();
            ApplicationBase.LocalData.edit()
                    .putInt(AppConfig.USER_ID, LoginUser.getInstance().getId())
                    .commit();
            ApplicationBase.LocalData.edit()
                    .putString("user_name", LoginUser.getInstance().getName())
                    .commit();

            JSONObject objCompany = jnb.getJSONObject("company_list");

            JSONArray companys_list = objCompany.getJSONArray("companys");
            JSONArray user_json = objCompany.getJSONArray("users");

            if (hasJsonData(companys_list.toString())) {
                EntityBase.createTableIfNotExist(Company.class);

                Type company_type = new TypeToken<List<Company>>() {
                }.getType();
                List<Company> company_list = new Gson().fromJson(
                        companys_list.toString(), company_type);

                if (company_list != null) {
                    for (Company company : company_list) {
                        Company local = EntityBase.findInstance(Company.class,
                                company.getId());
                        if (local != null) {
                            local.setDept_id(company.getDept_id());
                            local.setName(company.getName());
                            ApplicationBase.DbContext.update(local, "dept_id",
                                    "name"); // 只更新这两个字段，其他字段不能更新
                        } else {
                            ApplicationBase.DbContext.save(company);
                        }
                    }
                }
            }

            if (hasJsonData(user_json.toString())) {
                EntityBase.createTableIfNotExist(User.class);
                Type user_type = new TypeToken<List<User>>() {
                }.getType();
                List<User> user_list = new Gson().fromJson(
                        user_json.toString(), user_type);
                if (user_list != null) {
                    for (User user : user_list) { // user 参与人员
                        User local = EntityBase.findInstance(User.class,
                                user.getId());
                        if (local != null) {
                            local.setDept_id(user.getDept_id());
                            local.setName(user.getName());
                            ApplicationBase.DbContext.update(local, "dept_id",
                                    "name"); // 只更新这两个字段，其他字段不能更新
                        } else {
                            ApplicationBase.DbContext.save(user);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void login()
    {
        user = edtUser.getText().toString();
        pwd = edtPassword.getText().toString();

        if (pwd.isEmpty() || user.isEmpty()) {
//            Toast.makeText(LoginActivity.this, R.string.msg_empty_logininfo,
//                    Toast.LENGTH_SHORT).show();
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.cycle_edit);
            edtUser.startAnimation(shake);
            edtPassword.startAnimation(shake);


            return;
        }

//        清除缓存没有用
//        if (cbResetdb.isChecked()) {
//            resetDb();
//            cbResetdb.setChecked(false);
//        }


        // 检测网络
        if (ApplicationBase.checkNetworkAvailable()) {
            dialog = ProgressDialog.show(LoginActivity.this, null,
                    "拼命登录中，请稍候...", true, false);

            String url = AppConfig.TEXT_HOST + "/Api/Api/login/account/" + user
                    + "/password/" + pwd;
            VolleyRequest.jsonRequestGet(this, url, "hehe",
                    new JsonInterface<JSONObject>(this) {

                        @Override
                        public void jsonSuccess(JSONObject result) {
                            Log.e(TAG, "jsonSuccess: " +result);
                            try {
                                // 判断账号密码是否正确
                                int code = (Integer) result.get("code");
                                if (code == SUCCESS_CODE) {
                                    // 数据处理
                                    String jsonString = result.toString();
                                    if (hasJsonData(jsonString)) {
                                        parseJSON(jsonString);
                                    }

                                    JSONObject jnb = result
                                            .getJSONObject("message");
                                    JSONObject objUser = new JSONObject(jnb
                                            .getString("user"));
                                    // 获取用户的角色 ：5 主管 其他的普通维保人员
                                    int role = objUser
                                            .getInt("role_group_id");
                                    int type = -1;
                                    //获取账号平台类型
                                    if (!objUser.isNull("depart_type")) {
                                        type = objUser.getInt("depart_type");
                                    }
                                    //获取监管角色类型
                                    int jg_posi_id = 0;
                                    if (!objUser.isNull("jg_posi_id")) {
                                        jg_posi_id = objUser.getInt("jg_posi_id");
                                    }
                                    //获取调查人员的权限
                                    int access = 1;
                                    if (!objUser.isNull("assess")) {
                                        access = objUser.getInt("assess");
                                    }
                                    String depart_name = null;
                                    //获取账号平台名称
                                    if (!objUser.isNull("depart_name")) {
                                        depart_name = objUser.getString("depart_name");
                                    }
                                    // 保存用户信息
                                    UserInfoUtil.saveUserInfo(
                                            cbRemember.isChecked(),
                                            edtUser.getText().toString(),
                                            edtPassword.getText().toString(),
                                            ApplicationBase.LocalData
                                                    .getString(
                                                            AppConfig.ACCESS_TOKEN,
                                                            ""), role,type,depart_name, objUser
                                                    .getString("head_path"), objUser
                                                    .getString("name"), jg_posi_id,access);

                                    //根据账号的平台处理跳转
                                    gotoByRole(role);
                                    //关闭对话框
                                    if (dialog.isShowing())
                                        dialog.dismiss();

                                    try {
                                        //环信用户登录,失败不影响云上登录
                                        EaseMobHelp.getInstance().login(edtUser.getText().toString(), EaseMobHelp.password);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        Log.e("login", "环信登录失败");
                                    }

                                    //设置免打扰圈列表
                                    EaseMobHelp.getInstance().initUnBlockGroupId();


                                } else {
                                    Toast.makeText(LoginActivity.this,
                                            "账号或密码错误请重新输入。", Toast.LENGTH_LONG)
                                            .show();
                                    return;
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            } finally {
                                if (dialog != null && dialog.isShowing()) {
                                    dialog.dismiss();
                                }
                            }
                        }

                        @Override
                        public void josnError(VolleyError error) {
                            Toast.makeText(LoginActivity.this, "网络信号不好登入失败。",
                                    Toast.LENGTH_LONG).show();
                            if (dialog.isShowing())
                                dialog.dismiss();
                        }
                    });

        } else {
            if (userDao.find(user, pwd)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("提示");
                builder.setMessage("离线状态是否要登入!");
                builder.setPositiveButton("确认",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                try {
                                    List<Company> companys = ApplicationBase.DbContext
                                            .findAll(Company.class);
                                    if (null == companys || companys.size() < 0) {
                                        Toast.makeText(LoginActivity.this,
                                                "对不起!!!缓存没有数据。",
                                                Toast.LENGTH_LONG).show();
                                        return;
                                    }
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }
                                // startActivity(new Intent(LoginActivity.this,
                                // CompanySelectActivity.class));
//								startActivity(new Intent(LoginActivity.this,
//										MainActivity.class));
//								finish();
                            }
                        });
                builder.setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                            }

                        });
                builder.create().show();
            } else {
                Toast.makeText(this, "用户从来没登入过缓存没数据", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void regist()
    {
        Intent intent = new Intent(this,RegistActivity.class);
        startActivity(intent);
    }

    public void resetDb() {
        ApplicationBase.reCreateDatabase(this);
        AppConfig.SetSystemUpdateTime(0);
        ApplicationBase.XBitmap.clearCacheFiles();
    }

    private void restoreInputValue() {
        // 取sp里面的数据
        Boolean remember = ApplicationBase.LocalData.getBoolean(
                "input.remember", false);
        if (remember) {
            cbRemember.setChecked(true);
            String user = ApplicationBase.LocalData.getString("input.user", "");
            edtUser.setText(user);
            if (!user.isEmpty()) {
                String encryptPwd = ApplicationBase.LocalData.getString(
                        "input.password", "");
                // 加密、解密
                String Pwd = EncryptUtils.decryptDES(encryptPwd, user);
                edtPassword.setText(Pwd);
            }
        }
    }

    protected boolean hasJsonData(String json) {
        return !(json.equalsIgnoreCase("null") || json.equalsIgnoreCase("[]") || json
                .equalsIgnoreCase("{}"));
    }

    /**
     * @throws
     * @author: HYM
     * @Title: gotoByRole
     * @Description: TODO(根据不同的角色进入不同的界面)
     * @param: @param type
     * @return: void
     * @return: 2017-5-5
     */
    private void gotoByRole(int type) {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.putExtra("user_role", UserInfoUtil.getCurrentUserRole());
        startActivity(intent);
        new JPushUtil(this, UserInfoUtil.getCurrentUserAccount()).setJPushAlias();
    }

//	private void postJpushSuccessToServer()
//	{
//		Map<String, String> params = new HashMap<String, String>();
//		params.put(AppConfig.ACCESS_TOKEN,
//				UserInfoUtil.getCurrentUserAccessToken());
//		VolleyRequest.StringRequestPost(this,
//				WebApi.JPUSH_SET_TAG_ALISE_SUCCESS, "", params,
//				new StringInterface(this) {
//
//					@Override
//					public void stringSuccess(String result) {}
//
//					@Override
//					public void stringError(VolleyError error) {
//					}
//				});
//	}
}
